//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.eResearch.WFServiceLogger
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;

    /// <summary>
    /// This class is used to log the details to the log file.
    /// </summary>
    public class ServiceLogger
    {
        /// <summary>
        /// Log File path.
        /// </summary>
        private static string logFilePath = null;

        /// <summary>
        /// This initializes the logger with the Log file Path.
        /// </summary>
        /// <param name="logFileName">Log file path.</param>
        public static void InitLogger(string logFileName)
        {
            if (null != logFilePath)
            {
                return;
            }

            logFilePath = logFileName;
        }

        /// <summary>
        /// Write message to Log File.
        /// </summary>
        /// <param name="message">Message to be logged.</param>
        public static void WriteLogMessage(string message)
        {
            lock (logFilePath)
            {
                bool isDelete = false;

                if (File.Exists(logFilePath))
                {
                    using (FileStream fs = new FileStream(logFilePath, FileMode.Open))
                    {
                        if (fs.Length > 16384)
                        {
                            isDelete = true;
                        }
                    }

                    if (isDelete)
                    {
                        File.Delete(logFilePath);
                    }
                }

                StringBuilder formattedMsg = new StringBuilder();
                formattedMsg.Append(System.DateTime.Now);
                formattedMsg.Append(" : ");
                formattedMsg.Append(message);

                using (FileStream fs = new FileStream(logFilePath, FileMode.Append, FileAccess.Write))
                {
                    StreamWriter writer = new StreamWriter(fs);

                    writer.BaseStream.Seek(writer.BaseStream.Length, SeekOrigin.Begin);
                    writer.WriteLine(formattedMsg.ToString());
                    writer.Flush();
                    writer.Close();
                    writer.Dispose();
                }
            }
        }
    }
}
